'use strict';
var utils = require('../utils/utils.js');
var auth = require('../utils/auth.js');

// 网络异常代码
const ERR_NET_ERROR = -99999;
const ERR_ACCESS_TOKEN_EXPIRED = 20;
const ERR_NOT_ACCESS_TOKEN = 21;

// 取系统配置
var DEF_APP_CONFIG = {
  // 开发环境
  appId: "wx968d71a3d8e5558b",
  baseUrl: "https://dev.gomoretech.com",
  // baseUrl: "http://debenson.51vip.biz/newretail/api"
  // 演示环境
  // appId: "wx4211d71800f38996",
  // baseUrl: "https://dev.gomoretech.com/demo"
  // appId: "wx968d71a3d8e5558b",
  // baseUrl: "https://dev.gomoretech.com/newretail/api",
  // baseUrl: "http://debenson.51vip.biz/newretail/api"
}
const extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : DEF_APP_CONFIG;
const APP_ID = extConfig.appId || DEF_APP_CONFIG.appId;
const BASE_URL = extConfig.baseUrl || DEF_APP_CONFIG.baseUrl;

const APP_VERSION = 'wxapp-1.0.6.0'; // 当前小程序版本
const API_VERSION = '0.0.4'; // 当前API版本
const WXA_APPID = DEF_APP_CONFIG.appId; // 当前小程序的appid
var OS_VERSION = ''; // 当前微信操作系统版本
wx.getSystemInfo({
  success: function(res) {
    OS_VERSION = 'wxapp-' + res.version;
  }
})

/**
 * APP配置
 */
module.exports.APP_ID = APP_ID;
module.exports.BASE_URL = BASE_URL;

/**
 * 执行http请求
 */
module.exports.request = function(url, method = 'GET', data = {},
  contentType = 'json', dataType = 'json') {
  const self = this
  console.log(BASE_URL + url);
  var headers = {};
  if (contentType == 'json') {
    headers['content-type'] = 'application/json';
  } else {
    headers['content-type'] = 'application/x-www-form-urlencoded';
  }

  try {
    var value = wx.getStorageSync('wj_wxa_formId')
    console.log(value)
    if (value) {
      headers['wxa-form-id'] = value;
      wx.removeStorageSync('wj_wxa_formId')
    }
  } catch (e) {
    console.log(e)
    // Do something when catch error
  }

  headers['app-version'] = APP_VERSION;
  headers['os-version'] = OS_VERSION;
  headers['api-version'] = API_VERSION;
  headers['wxa-appid'] = WXA_APPID;

  // 添加access token，暂不支持刷新access token
  var tokens = auth.getTokens();
  if (tokens && tokens.accessToken) {
    headers['access-token'] = tokens.accessToken
  }

  function onSucc(res, resolve, reject) {
    // console.log(url + ' 请求成功返回: ' + JSON.stringify(res));

    var ok = (res.statusCode >= 200 && res.statusCode < 300);
    if (!ok) {
      reject({
        code: ERR_NET_ERROR,
        message: '网络错误'
      });
      return;
    }

    var userData = res.data;
    if (userData.code == 0) {
      // 如果成功，直接返回
      resolve(userData.data);
    } else {
      if (userData.code != ERR_ACCESS_TOKEN_EXPIRED) {
        if (userData.code != ERR_NOT_ACCESS_TOKEN) {
          // 直接失败
          reject(userData);
        } else {
          userData = {
            ...userData,
            message: '您还没有登录哦~'
          }
          reject(userData);
        }
      } else {
        // 特别处理Access Token已过期的异常： 重新登录后重放请求
        const postData = data //拿到上一次请求的参数
        self.login().then(data => {
          self.request(url, method, postData, contentType, dataType)
            .then(function(data) {
              resolve(data);
            }).catch(function(err) {
              reject(err);
            });
        }).catch(err => {
          auth.clearUserInfo()
          // reject(userData);
        })
      }
    }
  }

  return new Promise(function(resolve, reject) {
    if (!utils.isHideLoading()) {
      wx.showLoading();
    }
    const requestTask = wx.request({
      url: BASE_URL + url,
      method: method,
      dataType: dataType,
      data: data,
      header: headers,

      success: function(res) {
        onSucc(res, resolve, reject);
      },

      fail: function(res) {
        console.error(BASE_URL + url + ' 请求失败返回: ' + JSON.stringify(res));
        var message = res.errMsg;
        var code = -1
        if (message.indexOf("timeout") >= 0) {
          code = -1001
          requestTask.abort()
          message = "网络出小差了~";
        }
        if (message.indexOf("request:fail") >= 0) {
          message = "网络错误";
        }

        reject({
          code: code,
          message: message
        });
      },

      complete: function() {
        if (!utils.isHideLoading()) {
          wx.hideLoading();
        }
      }
    });
  });
}

/**
 * 小程序内部用户登录
 * 
 * @return code
 */
function wx_login() {
  return new Promise(function(resolve, reject) {
    wx.login({
      success: function(res) {
        console.debug('!!!微信登录返回结果-----' + JSON.stringify(res));
        if (res.code) {
          resolve(res.code);
        } else {
          reject({
            code: -1,
            message: res.errMsg
          });
        }
      },
      fail: function(res) {
        console.log(res);
        auth.clearUserInfo()
        reject({
          code: -1,
          message: res.errMsg
        });
      }
    });
  });
}

/**
 * 小程序内部取得用户信息
 * 
 * @return 用户信息
 */
function wx_getUserInfo() {
  return new Promise(function (resolve, reject) {
    wx.getUserInfo({
      success: function (res) {
        resolve(res);
      },
      fail: function (res) {
        console.log(res);
        reject({
          code: -1,
          message: res.errMsg
        });
      }
    })
  });
}

/**
 * 用户登录
 * 
 * @param decryptUserInfo 是否解密用户信息
 * @return 用户信息，如果返回的 #member字段为空，说明当前粉丝没有绑定手机号， 还不是会员。
 */
module.exports.login = function(decryptUserInfo = true) {
  var self = this;
  var loginCode = '';
  return wx_login()
    .then(function(code) {
      loginCode = code;
      return wx_getUserInfo()
    })
    .then(function(res) {
      var encryptedUserInfo = null;
      decryptUserInfo && (encryptedUserInfo = {
        encryptedData: res.encryptedData,
        iv: res.iv
      });
      var req = {
        appid: APP_ID,
        code: loginCode,
        encryptedUserInfo: encryptedUserInfo
      };
      return self.post('/newretail/api/wxa/login', req);
    })
    .then(function(data) {
      // 保存登录结果
      auth.setTokens(data);
      return data;
    });
}

/**
 * HTTP GET
 */
module.exports.get = function(url, data) {
  return this.request(url, 'GET', data);
}

/**
 * HTTP POST
 */
module.exports.post = function(url, data) {
  return this.request(url, 'POST', data);
}

/**
 * HTTP PUT
 */
module.exports.put = function(url, data) {
  return this.request(url, 'PUT', data);
}

/**
 * HTTP DELETE
 */
module.exports.delete = function(url, data) {
  return this.request(url, 'DELETE', data);
}